package com.magicode.portal.service.impl;

import java.security.Key;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.magicode.cms.entiy.base.Channel;
import com.magicode.cms.entiy.base.Dictionary;
import com.magicode.cms.entiy.base.Tag;
import com.magicode.cms.entiy.base.TvFilmPerson;
import com.magicode.cms.entiy.base.User;
import com.magicode.cms.entiy.base.Video;
import com.magicode.cms.entiy.base.VideoPlayHistory;
import com.magicode.common.assist.PropertiesUtil;
import com.magicode.common.dao.ICommonDaoService;
import com.magicode.common.dao.PageResults;
import com.magicode.common.util.DateUtil;
import com.magicode.common.util.EncryptUtil;
import com.magicode.portal.service.ISecVideoService;
import com.magicode.portal.service.PermissionService;

@Service("secVideoService")
@Transactional
public class SecVideoServiceImpl implements ISecVideoService {
	
	@Autowired
	@Qualifier("commonDaoService")
	private ICommonDaoService commonDaoService;
	
	@Autowired
	@Qualifier("portalpermissionService")
	private PermissionService permissionService;
	
	@Autowired
	@Qualifier("encryptUtil")
	private EncryptUtil encryptUtil;
	
	@Override
	public Video get(String id) {
		String hql = " from com.magicode.cms.entiy.base.Video v "
				+ " left join fetch v.channel "
				+ " left join fetch v.broadcaster "
				+ " left join fetch v.mainPic "
				+ " left join fetch v.compere "
				+ " left join fetch v.area "
				+ " left join fetch v.source "
				+ " left join fetch v.videoType "
				+ " left join fetch v.videoStatus "
				+ " left join fetch v.videoStyle "
				+ " left join fetch v.tags "
				+ " where v.id=? ";
		Video video = null;
		try {
			video = (Video) this.commonDaoService.getByHQL(hql, new String[]{id});
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(video != null){
			//去除视频主目录路径
			if(video.getVideoList()!=null && video.getVideoList().getPath()!=null){
				video.getVideoList().setPath(removeVideoCatalogue(video.getVideoList().getPath()));
			}
		}
		return video;
	}
	
	//去除视频主目录路径
	private String removeVideoCatalogue(String path){
		String video_catalogue = PropertiesUtil.parseStr("video_catalogue");
		path = path.replace(video_catalogue, "");
		return path;
	}
	
	@Override
	public PageResults getRelatedVideo(String id) {
		String vthql = " from com.magicode.cms.entiy.base.Video v left join fetch v.videoType where v.id=?";
		Video video = (Video) commonDaoService.getByHQL(vthql, new String[]{id});
		String hql = "";
		PageResults pageResults = new PageResults();
		List list = new ArrayList();
		if(video!=null && video.getVideoType()!=null){
			hql = " from com.magicode.cms.entiy.base.Video v "
				+ " left join fetch v.mainPic "
				+ " where  v.freeVideoList is not null  and v.videoType.id=? and v.id<>? order by v.createTime desc";
			pageResults = commonDaoService.findPageByFetchedHql(hql, null, 0, 10, new String[]{video.getVideoType().getId(),id});
		}else{
			//如果没有关联视频，取最热视频前5个
			if((pageResults.getResults()!=null && pageResults.getResults().size()<1) || pageResults.getResults()==null){
				pageResults = this.getHotVideo(id, 5);
			}else{
				List results = new ArrayList();
				pageResults.setResults(results);
			}
		}
		return pageResults;
	}

	//获取推荐视频
//	相同类型点击量得前6调
	@Override
	public PageResults getRecomFormatVideo(String id, Integer num , String[] channelCodes ){
		
		String hql = "";
		String selectHql = "select distinct v from "+Video.class.getName()+" v    "
				+ " left join fetch v.mainPic "
				+ " left join fetch v.area "
				+ " , "+Dictionary.class.getName()+" type ,"
				+ ""+Video.class.getName()+" t ";
		String whereHql = " where type in elements ( t.videoTypeList)  and t.freeVideoList is not null "
				+ " and  type in elements ( v.videoTypeList) "
				+ " and t.id =:id and v.id <> t.id  ";
		String orderHql = "  order by v.playCount desc , v.createTime desc ";
		PageResults pageResults = new PageResults();
		if(channelCodes != null && channelCodes.length > 0){
			whereHql += " and v.channel.code in ( ";
			String connectHql = "";
			for(String cCode : channelCodes){
				connectHql += "'"+cCode+"',"; 
			}
			connectHql = connectHql.substring(0, connectHql.length() -1 );
			whereHql += connectHql;
			whereHql += " ) ";
		}
		List list = new ArrayList();
		Map map = new HashMap();
		map.put("id", id);
		hql = selectHql + whereHql + orderHql;
		pageResults = commonDaoService.findPageByFetchedHqlMap(hql, null, 0, num, map);

		List results = null;
		//如果关联视频不足，剩余从最热视频获取，获取时排除已经获取的ID保证不重复
//		getHotVideoExcId();
		if((pageResults.getResults()!=null && pageResults.getResults().size()<num) || pageResults.getResults()==null){
			String[] ids = null;
			if(pageResults.getResults() != null && pageResults.getResults().size() > 0){
				ids = new String[pageResults.getResults().size()];
			}
			PageResults tempPr = this.getHotVideoExcId(id, num,ids,channelCodes);
			List tempList =  pageResults.getResults();
			if(tempList != null && tempPr != null && tempPr.getResults() != null ){
				tempList.addAll(tempPr.getResults());
			}
			
			pageResults.setResults(tempList);
		}
//		else{
//			results = new ArrayList();
//			pageResults.setResults(results);
//		}
		{
//		设置分类
			String typeHql = "select distinct new map(t.id as id , d.title as title ) "
					+ " from "+Dictionary.class.getName()+" d , "+Video.class.getName()+" t "
					+ " where  d in elements(t.videoTypeList)  " ;
			String propertyName = "videoTypesName";
			String connectStr = ",";
			try {
				pageResults = this.commonDaoService.getRelateProByList(typeHql, connectStr, propertyName, pageResults);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		{
//		设置标签
		String tagHql = "select distinct new map(t.id as id , d as title ) "
				+ " from "+Tag.class.getName()+" d , "+Video.class.getName()+" t "
				+ " where  d in elements(t.tags)  " ;
		String propertyName = "tags";
		String connectStr = null;
		try {
			pageResults = this.commonDaoService.getRelateProByList(tagHql, connectStr, propertyName, pageResults);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
		return pageResults;
	}

	@Override
	public PageResults getHotVideo(String id, Integer num) {
		String hql = " from com.magicode.cms.entiy.base.Video v "
				+ " left join fetch v.mainPic "
				+ " left join fetch v.area  "
				+ " where 1=1 and v.id<>? order by v.playCount desc, v.createTime desc";
		PageResults pageResults = commonDaoService.findPageByFetchedHql(hql, null, 1, num, new String[]{id});
		return pageResults;
	}

	@Override
	public PageResults getHotVideo(String id, Integer num ,String[] channelCodes) {
		String hql = " from com.magicode.cms.entiy.base.Video v "
				+ " left join fetch v.mainPic "
				+ " left join fetch v.area  "
				+ "  ";
		
		String whereHql = " where v.id<>? and  v.freeVideoList is not null ";
		String orderByHql = " order by v.playCount desc, v.createTime desc ";
		if(channelCodes != null && channelCodes.length > 0){
			whereHql += " and v.channel.code in ( ";
			String connectHql = "";
			for(String cCode : channelCodes){
				connectHql += "'"+cCode+"',"; 
			}
			connectHql = connectHql.substring(0, connectHql.length() -1 );
			whereHql += connectHql;
			whereHql += " ) ";
		}
		hql += whereHql + orderByHql;
		PageResults pageResults = commonDaoService.findPageByFetchedHql(hql, null, 1, num, new String[]{id});
		return pageResults;
	}

	/**
	 * 获取总数为：num-excIds.length，ID不为：id以及excIds的数据
	 */
	@Override
	public PageResults getHotVideoExcId(String id, Integer num ,String[] excIds, String[] channelCodes) {
		String hql = " from com.magicode.cms.entiy.base.Video v "
				+ " left join fetch v.mainPic "
				+ " left join fetch v.area  "
				+ "  ";
		
		String whereHql = " where v.id<>? and  v.freeVideoList is not null ";
		String orderByHql = " order by v.playCount desc, v.createTime desc ";
		if(excIds != null && excIds.length > 0){
			whereHql += " and v.id not in ( ";
			String connectHql = "";
			for(String excId : excIds){
				connectHql += "'"+excId+"',"; 
			}
			connectHql = connectHql.substring(0, connectHql.length() -1 );
			whereHql += connectHql;
			whereHql += " ) ";
		}
		if(channelCodes != null && channelCodes.length > 0){
			whereHql += " and v.channel.code in ( ";
			String connectHql = "";
			for(String cCode : channelCodes){
				connectHql += "'"+cCode+"',"; 
			}
			connectHql = connectHql.substring(0, connectHql.length() -1 );
			whereHql += connectHql;
			whereHql += " ) ";
		}
		hql += whereHql + orderByHql;
		int realNum = num;
		if(excIds != null && num > excIds.length){
			realNum = num - excIds.length;
		}
		PageResults pageResults = commonDaoService.findPageByFetchedHql(hql, null, 1, realNum, new String[]{id});
		return pageResults;
	}
	@Override
	public Boolean addPlayCount(Video video) {
		try {
			//增加播放次数
			Integer playCount = video.getPlayCount();
			if(playCount != null){
				playCount++;
				video.setPlayCount(playCount);
			}else{
				video.setPlayCount(1);
			}
			this.commonDaoService.update(video);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public Channel getVideoChannelCode(String id) {
		String hql = " select v.channel from com.magicode.cms.entiy.base.Video v  where v.id=? ";
		Channel channel = (Channel) commonDaoService.getByHQL(hql, new String[]{id});
		return channel;
	}

	@Override
	public void addHistory(String videoId, User user, Integer durationTime) {
		String hql = " from com.magicode.cms.entiy.base.VideoPlayHistory vh where vh.video.id=? and vh.user.id=? ";
		VideoPlayHistory playHistory  = (VideoPlayHistory) commonDaoService.getByHQL(hql, new String[]{videoId, user.getId()});
		if(playHistory!=null){
			playHistory.setDurationTime(durationTime);
			playHistory.setPlayTime(new Date());
		}else{
			playHistory = new VideoPlayHistory();
			Video video = new Video();
			video.setId(videoId);
			playHistory.setVideo(video);
			playHistory.setUser(user);
			playHistory.setDurationTime(durationTime);
			playHistory.setPlayTime(new Date());
		}
		this.commonDaoService.saveOrUpdate(playHistory);
	}

	@Override
	public Integer getVideoPlayTime(String videoId, User user) {
		if(user!=null && user.getId()!=null){
			String hql = " from com.magicode.cms.entiy.base.VideoPlayHistory vh where vh.video.id=? and vh.user.id=? ";
			VideoPlayHistory playHistory  = (VideoPlayHistory) commonDaoService.getByHQL(hql, new String[]{videoId, user.getId()});
			if(playHistory!=null)
				return playHistory.getDurationTime()==null?0:playHistory.getDurationTime();
		}
		return 0;
	}

	@Override
	public String converteTime(Integer Time) {
		int h = 0;
		int d = 0;
		int s = 0;
		int temp = Time % 3600;
		if (Time > 3600) {
			h = Time / 3600;
			if (temp != 0) {
				if (temp > 60) {
					d = temp / 60;
					if (temp % 60 != 0) {
						s = temp % 60;
					}
				} else {
					s = temp;
				}
			}
		} else {
			d = Time / 60;
			if (Time % 60 != 0) {
				s = Time % 60;
			}
		}
		String str = "";
		if(h!=0)
			str += h+"小时";
		if(d!=0)
			str += d+"分钟";
		if(s!=0)
			str += s+"秒";
		return str;  
	}

//	@Override
//	public String getPreviewTime(User user, Video video) {
//		String previewTime = "";
//		if(video != null){
////			仅通过设置视频时间控制观看时间；不再通过消费豆币控制
////			if(video.getResumeCoin()!=null && video.getResumeCoin() > 0){
//				Boolean b = false;
//				if(user!=null && video!=null){
//					b = permissionService.validVideoPermission(user.getId(), video.getId());
//				}
//				if(b){
//					previewTime = "null";//null表示不限制观看时间
//				}else{
//					if(video.getFreeViewTime()!=null){
//						previewTime = video.getFreeViewTime().toString();
//					}else{
//						previewTime = PropertiesUtil.parseStr("preview_time");
//					}
//				}
////			}else{
////				previewTime = "null";//null表示不限制观看时间
////			}
//		}
//		return previewTime;
//	}

	@Override
	public String getPreviewTime(User user, Video video) {
		String previewTime = "";
		if(video != null){
//			仅通过设置视频时间控制观看时间；不再通过消费豆币控制
//			if(video.getResumeCoin()!=null && video.getResumeCoin() > 0){
				Boolean b = false;
				if(user!=null && video!=null){
					b = permissionService.validVideoPermission(user.getId(), video.getId());
				}
				else if(user == null){
					b = permissionService.validVideoPermission(null, video.getId());
				}
				if(b){
					previewTime = "null";//null表示不限制观看时间
				}else{
					if(video.getFreeViewTime()!=null){
						previewTime = video.getFreeViewTime().toString();
					}else{
						previewTime = PropertiesUtil.parseStr("preview_time");
					}
				}
//			}else{
//				previewTime = "null";//null表示不限制观看时间
//			}
		}
		return previewTime;
	}
	@Override
	public Long getVideoCount() {
		String hql = " select count(*) from com.magicode.cms.entiy.base.Video v where v.freeVideoList is not null  ";
		Long count  = (Long) commonDaoService.getByHQL(hql, null);
		if(count!=null)
			return count;
		return 0L;
	}

	@Override
	public PageResults getInterestVideo(String id, Integer num) {
		String vthql = " from com.magicode.cms.entiy.base.Video v left join fetch v.area left join fetch v.videoType where v.id=?";
		Video video = (Video) commonDaoService.getByHQL(vthql, new String[]{id});
		String areaId = "";
		String videoTypeId = "";
		Map map = new HashMap();
		String hql = " from com.magicode.cms.entiy.base.Video v "
				+ " left join fetch v.mainPic "
				+ " where 1=1 and v.id<>:videoId and  v.freeVideoList is not null  "; 
		map.put("videoId", id);
		if(video != null){
			if("访谈".equals(video.getVideoType().getCode())){
				if(video.getVideoType() != null && video.getVideoType().getId()!=null){
					videoTypeId = video.getVideoType().getId();
					try {
						hql += " and v.videoType.id=:videoTypeId and v.createTime > '"+DateUtil.getInstance().countDate(-7)+"'";
					} catch (Exception e) {
						e.printStackTrace();
					}
					map.put("videoTypeId", videoTypeId);
				}
			}else{
				if(video.getArea() != null && video.getArea().getId()!=null){
					areaId = video.getArea().getId();
					hql += " and v.area.id=:areaId ";
					map.put("areaId", areaId);
				}
				if(video.getVideoType() != null && video.getVideoType().getId()!=null){
					videoTypeId = video.getVideoType().getId();
					hql += " and v.videoType.id=:videoTypeId ";
					map.put("videoTypeId", videoTypeId);
				}
			}
		}
		hql += " order by v.playCount desc, v.createTime desc";
		PageResults pageResults = new PageResults();
		pageResults = commonDaoService.findPageByFetchedHqlMap(hql, null, 0, num, map);
		//如果没有感兴趣视频，取最热视频前5个
		if((pageResults.getResults()!=null && pageResults.getResults().size()<1) || pageResults.getResults()==null){
			if("访谈".equals(video.getVideoType().getCode())){
				String allHql=" from com.magicode.cms.entiy.base.Video v "
						+ " left join fetch v.mainPic "
						+ " where 1=1 and v.id<>:videoId and v.freeVideoList is not null "; 
				map.put("videoId", id);
				if(video.getVideoType() != null && video.getVideoType().getId()!=null){
					allHql += " and v.videoType.id=:videoTypeId ";
					map.put("videoTypeId", videoTypeId);
				}
				allHql+=" order by v.playCount desc, v.createTime desc";
				pageResults=commonDaoService.findPageByFetchedHqlMap(allHql, null, 0, num, map);
			}else{
				pageResults = this.getHotVideo(id, 5);
			}
		}
		return pageResults;
	}

	@Override
	public Long getVideoCommentsNum(String id) {
		String hql = " select count(*) from com.magicode.cms.entiy.base.NewsComment n where n.news.id=? ";
		Long count  = (Long) commonDaoService.getByHQL(hql, new String[]{id});
		if(count!=null)
			return count;
		return 0L;
	}
	
	@Override
	public String encryptVideoPath(Video video){
		Date now = new Date();
		String nowTime = Long.valueOf(now.getTime()).toString();
		String videoListPath = "";
		if(video.getVideoList()!=null && video.getVideoList().getPath()!=null){
			videoListPath = video.getVideoList().getPath();
			videoListPath = videoListPath + "_secretTime_"+nowTime+"";
		}
		Key key = encryptUtil.getKeyFile();
		encryptUtil.setEncString(videoListPath);
		String ciphertext = encryptUtil.getStrMi();
		ciphertext = this.covertCiphertextForUrl(ciphertext);
		return ciphertext;
	}

	@Override
	public String covertCiphertextForUrl(String ciphertext) {
		System.out.println("before ciphertext:"+ciphertext);
		if(ciphertext!=null){
			ciphertext = ciphertext.replaceAll("/", "_SEC_SLASH");
			ciphertext = ciphertext.replaceAll("=", "_SEC_EQUAL");
			ciphertext = ciphertext.replaceAll("&", "_SEC_AND");
			ciphertext = ciphertext.replaceAll("%", "_SEC_PER");
			ciphertext = ciphertext.replaceAll("#", "_SEC_SIGN");
			ciphertext = ciphertext.replaceAll("\\?", "_SEC_QUEST");
			ciphertext = ciphertext.replaceAll("\\+", "_SEC_ADD");
			System.out.println("after ciphertext:"+ciphertext);
		}
		return ciphertext;
	}

	@Override
	public List<TvFilmPerson> getTvFilmPersonList(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public PageResults getTvFilmPerson(String id) {
		// TODO Auto-generated method stub
		return null;
	}

}

